/**
 * 全站路由配置
 *
 * 建议:
 * 1. 代码中路由统一使用name属性跳转(不使用path属性)
 */
import Vue from 'vue'
import Router from 'vue-router'
import http from '@/utils/httpRequest'
import { isURL } from '@/utils/validate'
import { clearLoginInfo } from '@/utils'

import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

NProgress.configure({ showSpinner: false })

Vue.use(Router)

// 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢, 所以只有生产环境使用懒加载
const _import = require('./import-' + process.env.NODE_ENV)

// 全局路由(无需嵌套上左右整体布局)
const globalRoutes = [
  {
    path: '/404',
    component: _import('common/404'),
    name: '404',
    meta: { title: '404未找到' }
  },
  {
    path: '/login',
    component: _import('common/login'),
    name: 'login',
    meta: { title: '登录' }
  }
]

// 主入口路由(需嵌套上左右整体布局)
const mainRoutes = {
  path: '/',
  component: _import('main'),
  name: 'main',
  redirect: { name: 'home' },
  meta: { title: '主入口整体布局' },
  children: [
    // 通过meta对象设置路由展示方式
    // 1. isTab: 是否通过tab展示内容, true: 是, false: 否
    // 2. iframeUrl: 是否通过iframe嵌套展示内容, '以http[s]://开头': 是, '': 否
    // 提示: 如需要通过iframe嵌套展示内容, 但不通过tab打开, 请自行创建组件使用iframe处理!
    {
      path: '/home',
      component: _import('common/home'),
      name: 'home',
      meta: { title: '首页' }
    }
    // { path: 'farmEvent/farmBrowse', component: _import('modules/farmEvent/farmBrowse'), name: 'farmBrowse', meta: { title: '' } },
  ],

  beforeEnter (to, from, next) {
    // console.log(Vue.cookie.get('Admin-Token'))
    let token = Vue.cookie.get('Admin-Token')
    // 上线需要打开注释

    // if (!token || !/\S/.test(token)) {
    //   clearLoginInfo()
    //   // window.location.href="http://localhost:8088"
    //   window.location.href = 'http://218.8.57.184:19099'
    //   // next({ name: 'login' })
    // }

    next()
  }
}

const router = new Router({
  mode: 'hash',
  scrollBehavior: () => ({ y: 0 }),
  isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
  routes: globalRoutes.concat(mainRoutes)
})

router.beforeEach((to, from, next) => {
  NProgress.start()
  // 添加动态(菜单)路由
  // 1. 已经添加 or 全局路由, 直接访问
  // 2. 获取菜单列表, 添加并保存本地存储
  if (
    router.options.isAddDynamicMenuRoutes ||
    fnCurrentRouteType(to, globalRoutes) === 'global'
  ) {
    next()
  } else {
    // 后期接口返回

    const menuList = [
      {
        menuId: 1,
        parentId: 0,
        parentName: null,
        name: '物资管理',
        url: null,
        perms: null,
        type: 0,
        icon: 'system',
        orderNum: 0,
        open: null,
        list: [
          {
            menuId: 2,
            parentId: 1,
            parentName: null,
            name: '物资分类',
            url: 'material/material',
            perms: null,
            type: 1,
            icon: 'admin',
            orderNum: 1,
            open: null,
            list: null
          },
          {
            menuId: 3,
            parentId: 1,
            parentName: null,
            name: '农资库存管理',
            url: 'stockControl/stockControl',
            perms: null,
            type: 1,
            icon: 'admin',
            orderNum: 1,
            open: null,
            list: null
          },
          {
            menuId: 4,
            parentId: 1,
            parentName: null,
            name: '物联网设备管理',
            url: 'iot/iot',
            perms: null,
            type: 1,
            icon: 'admin',
            orderNum: 1,
            open: null,
            list: null
          }
        ]
      },
      {
        menuId: 9,
        parentId: 0,
        parentName: null,
        name: '农事管理',
        url: 'farmEvent/farmEvent',
        perms: null,
        type: 0,
        icon: 'system',
        orderNum: 0,
        open: null
      },
      {
        menuId: 10,
        parentId: 0,
        parentName: null,
        name: '农情管理',
        url: 'farmWork/farmWork',
        perms: null,
        type: 0,
        icon: 'system',
        orderNum: 0,
        open: null
      }
    ]
    fnAddDynamicMenuRoutes(menuList)
    router.options.isAddDynamicMenuRoutes = true
    sessionStorage.setItem('menuList', JSON.stringify(menuList || '[]'))
    sessionStorage.setItem('permissions', '[]')
    next({ ...to, replace: true })
    next()

    // 上线需要打开注释

    // http({
    //   url: http.adornUrl('/oauth/get-session'),
    //   method: 'post',
    //   data: {}
    // }).then(({ data }) => {
    //   if (data && data.token) {
    //     // 获取菜单
    //     http({
    //       url: http.adornUrl('/oauth/user-app-permission/list-app-permission-by-user'),
    //       method: 'post',
    //       data: {
    //         user_id: data.user_id
    //       }
    //     }).then(res => {
    //       if (res.data.ret == '00000') {
    //         const menuList = fnParseMenuList(res.data.data)
    //         fnAddDynamicMenuRoutes(menuList)
    //         router.options.isAddDynamicMenuRoutes = true
    //         sessionStorage.setItem('menuList', JSON.stringify(menuList || '[]'))
    //         sessionStorage.setItem('permissions', '[]')
    //         next({ ...to, replace: true })
    //       } else {
    //         sessionStorage.setItem('menuList', '[]')
    //         sessionStorage.setItem('permissions', '[]')
    //         next()
    //       }
    //     }).catch(err => {
    //       console.log('菜单接口异常', err)
    //       next()
    //     })
    //   } else {
    //     // 未登录
    //     // window.location.href="http://localhost:8088"
    //     window.location.href = 'http://218.8.57.184:19099'
    //   }
    // }).catch((e) => {
    //   console.log(`%c${e} 请求菜单列表和权限失败，跳转至登录页！！`, 'color:blue')
    //   // window.location.href="http://localhost:8088"
    //   window.location.href = 'http://218.8.57.184:19099'
    // })
  }
}),

  function fnParseMenuList (menus) {
    let menuTree = []
    if (menus && menus.length > 0) {
      const menuArray = []
      menus.forEach(menu => {
        const obj = {
          menuId: menu.permission_id,
          parentId:
            menu.permission_pid && menu.permission_pid != null
              ? menu.permission_pid
              : 0,
          parentName: null,
          name: menu.permission_name,
          url: menu.component_route,
          perms: null,
          type: 0,
          icon: 'system',
          orderNum: menu.seq,
          open: null,
          list: null
        }
        menuArray.push(obj)
      })
      menuTree = toTree(menuArray, 0)
    }
    return menuTree
  }

function toTree (list, parId) {
  let len = list.length
  function loop (parId) {
    let res = []
    for (let i = 0; i < len; i++) {
      let item = list[i]
      if (item.parentId === parId) {
        item.list = loop(item.menuId)
        res.push(item)
      }
    }
    if (res.length == 0) {
      res = null
    }
    return res
  }
  return loop(parId)
}

/**
 * 判断当前路由类型, global: 全局路由, main: 主入口路由
 * @param {*} route 当前路由
 */
function fnCurrentRouteType (route, globalRoutes = []) {
  var temp = []
  for (var i = 0; i < globalRoutes.length; i++) {
    if (route.path === globalRoutes[i].path) {
      return 'global'
    } else if (
      globalRoutes[i].children &&
      globalRoutes[i].children.length >= 1
    ) {
      temp = temp.concat(globalRoutes[i].children)
    }
  }
  return temp.length >= 1 ? fnCurrentRouteType(route, temp) : 'main'
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function fnAddDynamicMenuRoutes (menuList = [], routes = []) {
  var temp = []
  for (var i = 0; i < menuList.length; i++) {
    if (menuList[i].list && menuList[i].list.length >= 1) {
      temp = temp.concat(menuList[i].list)
    } else if (menuList[i].url && /\S/.test(menuList[i].url)) {
      menuList[i].url = menuList[i].url.replace(/^\//, '')
      var route = {
        path: menuList[i].url.replace('/', '-'),
        component: null,
        name: menuList[i].url.replace('/', '-'),
        meta: {
          menuId: menuList[i].menuId,
          title: menuList[i].name,
          isDynamic: true,
          isTab: true,
          iframeUrl: ''
        }
      }
      // url以http[s]://开头, 通过iframe展示
      if (isURL(menuList[i].url)) {
        route['path'] = `i-${menuList[i].menuId}`
        route['name'] = `i-${menuList[i].menuId}`
        route['meta']['iframeUrl'] = menuList[i].url
      } else {
        try {
          route['component'] = _import(`modules/${menuList[i].url}`) || null
        } catch (e) { }
      }
      routes.push(route)
    }
  }
  if (temp.length >= 1) {
    fnAddDynamicMenuRoutes(temp, routes)
  } else {
    mainRoutes.name = 'main-dynamic'
    mainRoutes.children = routes
    router.addRoutes([mainRoutes, { path: '*', redirect: { name: '404' } }])
    sessionStorage.setItem(
      'dynamicMenuRoutes',
      JSON.stringify(mainRoutes.children || '[]')
    )
    console.log('\n')
    console.log(
      '%c!<-------------------- 动态(菜单)路由 s -------------------->',
      'color:blue'
    )
    console.log(mainRoutes.children)
    console.log(
      '%c!<-------------------- 动态(菜单)路由 e -------------------->',
      'color:blue'
    )
  }
}

router.afterEach(() => {
  NProgress.done()
})

export default router
